import { _decorator, BoxCollider, Component, ITriggerEvent, Node } from 'cc';
import { Constand } from './Constant';
import { GameManager } from './GameManager';
import { AuidoManager } from './AuidoManager';
import { PoolMananger } from './PoolMananger';
import { Bullet } from './Bullet';
import { SelPlane } from './SelPlane';
const { ccclass, property } = _decorator;

const OUTOFRANGE = 130;
@ccclass('EnemyPlane')
export class EnemyPlane extends Component implements IDamage {
    @property
    public damage: number = 1;
    private _speed = 0;

    @property
    public createBulletTime = 0.5;
    public enemyType = Constand.EnemyType.TYPE1;
    private _needBullet = false;
    private _currBulletTime = 0;
    //敌机类型
    @property
    public type = 1;
    //敌机血量
    @property
    public hp = 10;
    onEnable() {
        const collider = this.getComponent(BoxCollider);
        collider.on('onTriggerEnter', this._onTriggerEnter, this);
    }

    onDisable(): void {
        const collider = this.getComponent(BoxCollider);
        collider.off('onTriggerEnter', this._onTriggerEnter, this);
    }

    private _onTriggerEnter(event: ITriggerEvent) {
        const grop = event.otherCollider.getGroup();
        let damage = 0;
        if (grop == Constand.CollistionType.PLAYER) {
            const com = event.otherCollider.getComponent(SelPlane);
            damage = com.damage;
        } else if (grop == Constand.CollistionType.BULLET) {
            const com = event.otherCollider.getComponent(Bullet);
            damage = com.damage;
        }
        this.hp -= damage;
        if(this.hp <= 0){
            GameManager.getInstance().addScore();
            AuidoManager.getInstance().play("enemy");
            PoolMananger.getInstance().putNode(this.node);
            GameManager.getInstance().createExplode(this.node.position, 2);
        }
    }

    update(deltaTime: number) {
        const pos = this.node.position;
        const movePos = pos.z + this._speed * deltaTime
        this.node.setPosition(pos.x, pos.y, movePos);
        if (movePos > OUTOFRANGE) {
            PoolMananger.getInstance().putNode(this.node);
        }
        if (this._needBullet) {
            this._currBulletTime += deltaTime;
            if (this._currBulletTime > this.createBulletTime) {
                GameManager.getInstance().createEnemyBullet(this.node.position, this.type);
                this._currBulletTime = 0
            }
        }
    }

    setSpeed(value: number, needbullet: boolean) {
        this._speed = value;
        this._needBullet = needbullet;
    }


}


